<!--
  智慧社区管理系统 - 权限监控页面
  @author Wu.Liang
  @date 2024-12-21
  @description 权限检查统计和监控数据展示
-->
<template>
  <div class="permission-monitor">
    <!-- 页面标题和描述 -->
    <div class="page-header">
      <div class="page-title">
        <h1>权限监控</h1>
        <p class="page-desc">监控权限检查失败情况，查看权限使用统计和预警信息</p>
      </div>
      <div class="page-actions">
        <el-button type="primary" :icon="Refresh" @click="refreshData">
          刷新数据
        </el-button>
        <el-button :icon="Download" @click="exportData">
          导出报告
        </el-button>
      </div>
    </div>

    <!-- 统计卡片区域 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon size="32" color="#409EFF">
                  <Warning />
                </el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ stats.totalFailures }}</div>
                <div class="stat-label">总失败次数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon size="32" color="#E6A23C">
                  <Key />
                </el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ stats.uniquePermissions }}</div>
                <div class="stat-label">涉及权限数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon size="32" color="#67C23A">
                  <User />
                </el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ stats.uniqueUsers }}</div>
                <div class="stat-label">涉及用户数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon size="32" color="#F56C6C">
                  <Clock />
                </el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ timeWindowText }}</div>
                <div class="stat-label">监控时间窗口</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 权限缓存管理 -->
    <div class="cache-section">
      <el-card shadow="never">
        <template #header>
          <div class="card-header">
            <span>权限缓存管理</span>
            <PermissionCacheManager 
              :show-status="true"
              :show-actions="true"
              :show-details="true"
              :auto-refresh-interval="300000"
            />
          </div>
        </template>
      </el-card>
    </div>

    <!-- 失败记录列表 -->
    <div class="failure-records">
      <el-card shadow="never">
        <template #header>
          <div class="card-header">
            <span>权限检查失败记录</span>
            <div class="header-actions">
              <el-button size="small" @click="clearRecords">
                清空记录
              </el-button>
              <el-button size="small" @click="exportRecords">
                导出记录
              </el-button>
            </div>
          </div>
        </template>

        <el-table 
          v-loading="loading" 
          :data="failureRecords" 
          stripe 
          border
          max-height="500"
        >
          <el-table-column prop="permission" label="权限编码" min-width="150" />
          <el-table-column prop="username" label="用户名" width="120" />
          <el-table-column prop="context" label="失败上下文" min-width="150" />
          <el-table-column prop="url" label="访问地址" min-width="200" show-overflow-tooltip />
          <el-table-column prop="timestamp" label="失败时间" width="180">
            <template #default="{ row }">
              {{ formatTime(row.timestamp) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link size="small" @click="viewDetail(row)">
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 空状态 -->
        <el-empty 
          v-if="!loading && failureRecords.length === 0" 
          description="暂无权限检查失败记录"
          :image-size="120"
        />
      </el-card>
    </div>

    <!-- 详情弹窗 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="失败详情" 
      width="600px"
    >
      <div v-if="currentRecord" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="权限编码">
            {{ currentRecord.permission }}
          </el-descriptions-item>
          <el-descriptions-item label="用户名">
            {{ currentRecord.username }}
          </el-descriptions-item>
          <el-descriptions-item label="失败上下文">
            {{ currentRecord.context }}
          </el-descriptions-item>
          <el-descriptions-item label="失败时间">
            {{ formatTime(currentRecord.timestamp) }}
          </el-descriptions-item>
          <el-descriptions-item label="访问地址" :span="2">
            {{ currentRecord.url }}
          </el-descriptions-item>
          <el-descriptions-item label="用户代理" :span="2">
            {{ currentRecord.userAgent }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
/**
 * 权限监控页面
 * @author Wu.Liang
 * @date 2024-12-21
 * @description 监控权限检查失败情况，查看权限使用统计和预警信息
 */
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Refresh, 
  Download, 
  Warning, 
  Key, 
  User, 
  Clock 
} from '@element-plus/icons-vue'
import PermissionCacheManager from '@/components/PermissionCacheManager.vue'
import { PermissionMonitor, usePermissionMonitor, type PermissionLogItem } from '@/utils/permissionMonitor'
import { showSuccess, showError, showInfo, showWarning } from '@/utils/message'

// 响应式数据
const loading = ref(false)
const detailDialogVisible = ref(false)
const currentRecord = ref<PermissionLogItem | null>(null)

// 统计数据
const stats = ref({
  totalFailures: 0,
  uniquePermissions: 0,
  uniqueUsers: 0,
  timeWindow: 5 * 60 * 1000 // 5分钟
})

// 失败记录
const failureRecords = ref<PermissionLogItem[]>([])

// 计算属性
const timeWindowText = computed(() => {
  const minutes = Math.floor(stats.value.timeWindow / (1000 * 60))
  return `${minutes}分钟`
})

// 方法
const refreshData = () => {
  loading.value = true
  
  try {
    // 获取权限日志
    const logs = PermissionMonitor.getLogs()
    const errorLogs = logs.filter(log => !log.result)
    
    // 统计失败次数
    stats.value.totalFailures = errorLogs.length
    
    // 统计涉及权限数
    const uniquePermissions = new Set(errorLogs.map(log => log.permission || 'unknown'))
    stats.value.uniquePermissions = uniquePermissions.size
    
    // 统计涉及用户数
    const uniqueUsers = new Set(errorLogs.map(log => log.username || 'unknown'))
    stats.value.uniqueUsers = uniqueUsers.size
    
    // 设置失败记录
    failureRecords.value = errorLogs
    
    showSuccess('数据刷新成功')
  } catch (error) {
    console.error('刷新数据失败:', error)
    showError('数据刷新失败')
  } finally {
    loading.value = false
  }
}

const exportData = () => {
  showInfo('导出功能开发中')
}

const clearRecords = () => {
  try {
    PermissionMonitor.clearLogs()
    refreshData()
    showSuccess('记录已清空')
  } catch (error) {
    console.error('清空记录失败:', error)
    showError('清空记录失败')
  }
}

const exportRecords = () => {
  showInfo('导出记录功能开发中')
}

const viewDetail = (record: PermissionLogItem) => {
  currentRecord.value = record
  detailDialogVisible.value = true
}

const formatTime = (timestamp: number) => {
  return new Date(timestamp).toLocaleString('zh-CN')
}

// 页面加载时初始化数据
onMounted(() => {
  refreshData()
})
</script>

<style lang="scss" scoped>
.permission-monitor {
  padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    .page-title {
      h1 {
        font-size: 24px;
        font-weight: 600;
        color: #303133;
        margin: 0 0 8px 0;
      }
      
      .page-desc {
        font-size: 14px;
        color: #606266;
        margin: 0;
      }
    }
    
    .page-actions {
      display: flex;
      gap: 12px;
    }
  }
  
  .stats-cards {
    margin-bottom: 24px;
    
    .stat-card {
      .stat-content {
        display: flex;
        align-items: center;
        gap: 16px;
        
        .stat-icon {
          flex-shrink: 0;
        }
        
        .stat-info {
          flex: 1;
          
          .stat-value {
            font-size: 28px;
            font-weight: 600;
            color: #303133;
            line-height: 1;
            margin-bottom: 4px;
          }
          
          .stat-label {
            font-size: 14px;
            color: #909399;
          }
        }
      }
    }
  }
  
  .cache-section {
    margin-bottom: 24px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
  
  .failure-records {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-actions {
        display: flex;
        gap: 8px;
      }
    }
  }
  
  .detail-content {
    .el-descriptions {
      margin-top: 16px;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .permission-monitor {
    padding: 16px;
    
    .page-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 16px;
      
      .page-actions {
        width: 100%;
        justify-content: flex-end;
      }
    }
    
    .stats-cards {
      .el-col {
        margin-bottom: 16px;
      }
    }
  }
}
</style> 